package com.github.cyf.common.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author chenyifan
 * @create 2025-05-22 16:01
 */
@Configuration
public class ThreadPoolConfig {

    @Value("${upload.threadMaxSize}")
    private int threadMaxSize;

    @Value("${upload.queueMaxSize}")
    private int queueMaxSize;

    @Bean("uploadExecutorService")
    public CompletionService uploadExecutorService(){
        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
                threadMaxSize,
                threadMaxSize,
                0L,
                TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<>(queueMaxSize),
                new ThreadFactory() {
                    private final AtomicInteger atomicInteger = new AtomicInteger(1);

                    @Override
                    public Thread newThread(Runnable r) {
                        String threadName = "uploadPool-" + atomicInteger.getAndIncrement();
                        Thread thread = new Thread(r);
                        thread.setName(threadName);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
        return new ExecutorCompletionService(threadPool);
    }
}
